package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author kabuda
 * @create 2022-08-22 22:17
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    OrderService orderService;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //从redis获取保存的验证码
        String validateCodeRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //比对用户输入的验证码
        if(validateCode!=null&&validateCodeRedis!=null&&validateCodeRedis.equals(validateCode)){
            map.put("orderType",Order.ORDERTYPE_WEIXIN);
            //如果成功，调用业务层完成预约业务处理
            Result result=null;
            try{
                //预约
              result= orderService.order(map);
                //如果预约成功，发送预约成功消息
                if(result.isFlag()){
                    //String[] telephones= new String[]{telephone};
                    //String orderDate = (String) map.get("orderDate");
                    //String[] params= new String[]{"1111"};
                    //SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephones,params);
                }
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false, MessageConstant.ORDERSETTING_FAIL);
            }
            return result;
        }else{
            //如果比对不成功，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
    @RequestMapping("/findById")
    public Result findById(@RequestParam("id") Integer id){
        try{
            Map orderMap = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,orderMap);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
